package com.example.phone.search;

import android.content.Intent;
import android.view.View;

import com.example.phone.R;
import com.example.phone.base.ActivityCollector;
import com.example.phone.base.BaseActivity;
import com.example.phone.base.RequestInterface;
import com.example.phone.base.ServerResponse;
import com.example.phone.bean.MyPageInfo;
import com.example.phone.bean.SearchResult;
import com.example.phone.utils.SharedPreferenceUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mancj.materialsearchbar.MaterialSearchBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class SearchActivity extends BaseActivity implements MaterialSearchBar.OnSearchActionListener{
    private List<String> lastSearches;
    private Gson gson = new Gson();
    @BindView(R.id.searchBar)
    MaterialSearchBar searchBar;

    @Override
    public void initData() {

    }

    @Override
    public void initView() {
        ButterKnife.bind(this);

        searchBar.setSpeechMode(false);
        searchBar.setOnSearchActionListener(this);
        searchBar.setHint("请输入商品关键字");
        lastSearches = loadSearchSuggestionFromDisk();
        if (lastSearches != null) {
            searchBar.setLastSuggestions(lastSearches);
        }

    }

    @Override
    public int initLayout() {
        return R.layout.activity_search;
    }

    @Override
    protected void onDestroy() {
        ActivityCollector.removeActivity(this);
        super.onDestroy();
        saveSearchSuggestionToDisk((List<String>)searchBar.getLastSuggestions());
    }


    private void getSearchResult(CharSequence text) {
        final String keyword = text.toString().replace(" ", "");
        log("send Request");
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RequestInterface.basePath)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestInterface.SearchRequest searchRequest = retrofit.create(RequestInterface.SearchRequest.class);
        Call<ServerResponse<MyPageInfo<SearchResult>>> call = searchRequest.getProductList(keyword, 1, 10);
        call.enqueue(new Callback<ServerResponse<MyPageInfo<SearchResult>>>() {
            @Override
            public void onResponse(Call<ServerResponse<MyPageInfo<SearchResult>>> call, Response<ServerResponse<MyPageInfo<SearchResult>>> response) {
                if (response.body().getStatus() == 0) {
                    MyPageInfo<SearchResult> pageInfo = response.body().getData();

                    if (pageInfo != null) {
                        List<SearchResult> list = pageInfo.getList();
                        if (list != null && list.size() > 0) {
                           Intent intent = new Intent(getContext(), SearchDetailActivity.class);
                           intent.putExtra("keyword", keyword);
                           startActivity(intent);
                        } else {
                            toastShort("抱歉，没有找到相应的产品");
                        }
                    } else {
                        toastShort("抱歉，没有找到相应的产品");
                    }
                } else {
                    toastShort("搜索失败，请检查网络");
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<MyPageInfo<SearchResult>>> call, Throwable t) {
                toastShort("购物车加载失败，请检查网络");
            }
        });
    }




    private void saveSearchSuggestionToDisk(List<String> Suggestions) {
        String jsonSuggestions = gson.toJson(Suggestions);
        SharedPreferenceUtil.put(this, "lastSuggestions", jsonSuggestions);
    }

    private List<String> loadSearchSuggestionFromDisk() {
        String jsonSuggestions = (String) SharedPreferenceUtil.get(this, "lastSuggestions", "");

        return gson.fromJson(jsonSuggestions, new TypeToken<List<String>>(){}.getType());
    }




    @Override
    public void onSearchStateChanged(boolean enabled) {

    }

    @Override
    public void onSearchConfirmed(CharSequence text) {
        if (text == null || text.toString().isEmpty()) {
            toastShort("关键字不能为空");
        } else {
            getSearchResult(text);
        }
    }

    @Override
    public void onButtonClicked(int buttonCode) {

    }
}
